package edu.vt.ece4564.bluetendance.attendance;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;

import edu.vt.ece4564.bluetendance.database.DatabaseConnector;

public class ClassAttendanceGetter implements Runnable {

	private HttpServletResponse response;
	private String className;
	private String date;

	public ClassAttendanceGetter(HttpServletResponse response, String className, String date) {
		this.response = response;
		this.className = className;
		this.date = date;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void run() {
		DatabaseConnector dc = DatabaseConnector.get();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
		
		Date theDate = null;
		try {
			theDate = sdf.parse(date);
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		
		dc.commandText = "call SP_GetClassAttendance('" + className + "', '" + date + "');";
		ResultSet results = dc.executeQuery();
		
		List<AttendanceRecord> attendanceRecords = new ArrayList<AttendanceRecord>();
		
		try {
			while (results.next()) {
				attendanceRecords.add(new AttendanceRecord(results.getInt("StudentID"), results.getString("StudentName"), results.getBoolean("Present")));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		response.setContentType("text/html;charset=UTF-8");

		PrintWriter out = null;
		
		try {
			out = response.getWriter();
		}
		catch (IOException e) {
			e.printStackTrace();
		}

		if (attendanceRecords.size() > 0) {
			String result = "";
			
			for (AttendanceRecord attendanceRecord : attendanceRecords) {
				result += "<h3>";
				String present;
				if (attendanceRecord.getPresent()) {
					present = " was present.";
				}
				else {
					present = " was not present.";
				}
				
				result += attendanceRecord.getStudentName();
				result += present;
				result += "</h3>";
			}
			out.println(result);
		}
		else {
			JSONObject obj=new JSONObject();

			obj.put("valid","false");
			out.println(obj.toString());
		}
		out.close();
	}
}
